package com.heeexy.example.controller.web;


import com.google.code.kaptcha.Producer;
import com.heeexy.example.service.UserService;

import com.heeexy.example.util.javaSendMail;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import yinwei.bo.common.Constants.Constans;
import yinwei.bo.common.entry.uList;
import yinwei.bo.common.entry.vo.loginVo;
import yinwei.bo.common.exception.Assert;
import yinwei.bo.common.result.R;
import yinwei.bo.common.result.ResponseEnum;
import yinwei.bo.common.util.RandomUtils;
import yinwei.bo.common.util.RegexValidateUtils;
import yinwei.bo.common.util.base64;
import yinwei.bo.common.util.redisCache;
import yinwei.bo.common.util.uuid.Idutils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("User")
public class UserLoginController {

    @Resource
    private Producer captchaProducer;

    @Resource
    private Producer captchaProducerMath;

    @Value("${yaomi.captchaType}")
    private String captchaType;

    @Resource
    private yinwei.bo.common.util.redisCache redisCache;

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserService userService;

    @RequestMapping("/Sign")
    public R register(@RequestBody uList uList) {
        userService.register(uList);
        //Assert.notEmpty();
        return R.ok().message("注册成功");
    }

    @RequestMapping("yLogin")
    public R yLogin(){

        return R.ok();
    }
    @RequestMapping("Login")
    public R login(@RequestBody loginVo loginVo){

        return R.ok();
    }
    @RequestMapping("/captcha")
    public R captcha(@RequestBody String mobile){
        String code=RandomUtils.getFourBitRandom();
        // 校验手机号是否为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        // 校验手机号是否合法
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        /*// 按断手机号是否已经被注册（这是一次远程调用）
        boolean result = coreUserInfoClient.checkMobile(mobile);
        Assert.isTrue(!result, ResponseEnum.MOBILE_EXIST_ERROR);*/
        redisTemplate.opsForValue().set("xyw:sms:code:" + mobile, code, 5, TimeUnit.MINUTES);
        javaSendMail javaSendMail=new javaSendMail();
        javaSendMail.sendEmail("验证码",mobile,code);
        return R.ok();
    }
    @GetMapping("/captchaImage")
    public R getCode(HttpServletResponse response) throws IOException
    {
        // 保存验证码信息
        String uuid = Idutils.simpleUUID();
        String verifyKey = Constans.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constans.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return R.error().message(e.getMessage());
        }

        Map<String,Object> imgResult = new HashMap<String,Object>(2);
        imgResult.put("uuid", uuid);
        imgResult.put("img", base64.encode(os.toByteArray()));
        return R.ok().data(imgResult);
    }

}
